package com.sinosoft.userprovider.services.impl;

import com.sinosoft.userprovider.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.sinosoft.dto.UserDto;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Wenzheng.Ma
 * @desc
 * @date 2018/04/17 17:20
 */
@Transactional
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int saveUser(UserDto dto) {
        String sql=" insert into tuser values('"+dto.getUsername()+"','"+dto.getPassword()+"','"+dto.getUsercode()+"')";
        return jdbcTemplate.update(sql);
    }

    @Override
    public int updateUser(UserDto dto) {
        StringBuffer sql=new StringBuffer(" update table tuser set ");
        if(dto.getPassword()!=null){
            sql.append(" and password ='"+dto.getPassword()+"' ");
        }
        if(dto.getUsername()!=null){
            sql.append(" and username ='"+dto.getUsername()+"' ");
        }
        if(dto.getUsercode()!=null){
            sql.append("  where usercode ='"+dto.getUsercode()+"' ");
        }
        return jdbcTemplate.update(sql.toString());
    }

    @Override
    public int removeUser(UserDto dto) {
        return jdbcTemplate.update("DELETE FROM tuser WHERE usercode ='"+dto.getUsercode()+"'");
    }

    @Override
    public UserDto getUser(UserDto dto) {
        List<UserDto> list=jdbcTemplate.query("select * from tuser s where 1=1 and s.usercode = '"+dto.getUsercode()+"'",
                (rs, rowNum) -> new UserDto(rs.getString("username"),
                rs.getString("password"), rs.getString("usercode")));
        return list.size()>0?list.get(0):null;
    }

    @Override
    public List<UserDto> listUser(UserDto dto) {
        StringBuffer sql=new StringBuffer("select * from tuser s where 1=1");
        if(dto.getUsercode()!=null){
           sql.append("and s.usercode = '"+dto.getUsercode()+"'");
        }
        if(dto.getUsername()!=null){
            sql.append("and s.username = '"+dto.getUsercode()+"'");
        }
        List<UserDto> list=jdbcTemplate.query(sql.toString(),
                (rs, rowNum) -> new UserDto(rs.getString("username"),
                        rs.getString("password"), rs.getString("usercode")));
        return list;
    }
}
